package com.yokead.controller.digging;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HtmlUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.odiszapc.nginxparser.NgxBlock;
import com.github.odiszapc.nginxparser.NgxConfig;
import com.github.odiszapc.nginxparser.NgxEntry;
import com.github.odiszapc.nginxparser.NgxParam;
import com.yokead.common.Config;
import com.yokead.common.base.DiggingBaseControl;
import com.yokead.common.tools.UrlPath;
import com.yokead.controller.copy.AddStatusControl;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import com.yokead.util.EncryptUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.List;
import java.util.Stack;

/**
 * Created by jiangzeyin on 2017/7/4.
 */
@Controller
@RequestMapping("digging")
public class DiggingTypeControl extends DiggingBaseControl {

    @RequestMapping(value = "save_info.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin(String tag, String name, String context, boolean cover) {
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            File file = new File(path);
            if (!file.exists()) {
                return JsonMessage.getString(400, "不存在该信息");
            }
            if (StringUtil.isChinese(name)) {
                return JsonMessage.getString(400, "产品名称不能为中文");
            }
            if (StringUtil.isEmpty(context)) {
                return JsonMessage.getString(400, "内容不能为空");
            }
            File pr = new File(file, name);
            if (!cover) {
                if (pr.exists()) {
                    return JsonMessage.getString(400, "产品名已经存在");
                }
            } else {
                backIndexHtml(pr);
            }
            pr = new File(pr, "index.html");
            context = HtmlUtil.unescape(StringUtil.compileHtml(context));
            FileUtil.writeString(context, pr, CharsetUtil.CHARSET_UTF_8);
            return JsonMessage.getString(200, "保存成功");
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("扒取失败", e);
            return JsonMessage.getString(500, "保存失败:" + e.getMessage());
        }
    }

    /**
     * 添加状态文案
     *
     * @param tag
     * @param status
     * @param context
     * @return
     */
    @RequestMapping(value = "save_info_status.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_info_status(String tag, String status, String context) {
        String json = AddStatusControl.checkTag(tag, status);
        if (json != null) {
            return json;
        }
        String path;
        try {
            path = EncryptUtil.decrypt(tag);
            UrlPath.Type url = UrlPath.Type.Url;
            url.setPath(path);
            JSONArray jsonArray = UrlPath.start(Config.Nginx.getNginxConfigPath(), url);
            if (jsonArray.size() != 1) {
                return JsonMessage.getString(200, "文案存在冲突");
            }
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String rurl = jsonObject.getString("urls");
            String product = jsonObject.getString("product");
            if (StringUtil.isEmpty(rurl)) {
                rurl = jsonObject.getString("url");
                int s = rurl.indexOf("://");
                String tempStr = rurl.substring(s + 1);
                rurl = tempStr.substring(0, tempStr.indexOf("/"));
                rurl += "/" + product + "/index_" + status + ".html";
                rurl = StringUtil.clearPath(rurl);
            }
            context = HtmlUtil.unescape(StringUtil.compileHtml(context));
            File file = new File(path);
            File sFile = new File(file.getParent(), "index_" + status + ".html");
            FileUtil.writeString(context, sFile.getPath(), CharsetUtil.CHARSET_UTF_8);
            return JsonMessage.getString(200, "保存成功", rurl);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存失败", e);
            return JsonMessage.getString(500, "保存失败:" + e.getMessage());
        }
    }

    @RequestMapping(value = "getUserDomain.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_weixin(String name) throws Exception {
        name = convertFilePath(name);
        File file = new File(Config.Nginx.getNginxConfigPath(), name);
        if (!file.exists() || file.isFile()) {
            return JsonMessage.getString(100, "没有对应数据");
        }
        Stack<File> stack = new Stack<>();
        stack.push(file);
        JSONArray jsonArray = new JSONArray();
        // 遍历类路径
        while (!stack.isEmpty()) {
            File item = stack.pop();
            File[] subFile = item.listFiles((dir, name_) -> new File(dir, name_).isFile() && name_.endsWith(".conf"));
            if (subFile == null) {
                continue;
            }
            for (File itemFile : subFile) {
                if (itemFile.isDirectory()) {
                    stack.push(itemFile);
                } else {
                    NgxConfig conf = NgxConfig.read(itemFile.getPath());
                    List<NgxEntry> locations = conf.findAll(NgxConfig.BLOCK, "server", "location");
                    NgxParam server_name = conf.findParam("server", "server_name");
                    if (server_name == null) {
                        continue;
                    }
                    List<String> stringList = server_name.getValues();
                    if (stringList == null) {
                        continue;
                    }
                    StringBuilder urlName = new StringBuilder();
                    for (String itemUrl : stringList) {
                        if (urlName.length() > 1) {
                            urlName.append(",");
                        }
                        urlName.append(itemUrl);
                    }
                    if (locations == null) {
                        continue;
                    }
                    out:
                    for (NgxEntry ngxEntry : locations) {
                        if (ngxEntry instanceof NgxBlock) {
                            NgxBlock block = (NgxBlock) ngxEntry;
                            NgxParam root = block.findParam("root");
                            if (root == null) {
                                root = block.findParam("alias");
                                if (root == null) {
                                    continue;
                                }
                            }
                            List<String> rootValues = root.getValues();
                            if (rootValues == null || rootValues.size() != 1) {
                                continue;
                            }
                            String rootPath = rootValues.get(0);
                            JSONArray exclude_resolve_path = Config.Nginx.getExcludeResolvePath();
                            if (exclude_resolve_path != null) {
                                for (Object object : exclude_resolve_path) {
                                    String path = StringUtil.convertNULL(object);
                                    if (rootPath.startsWith(path)) {
                                        continue out;
                                    }
                                }
                            }
                            String[] paths = StringUtil.stringToArray(rootPath, "/");
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("name", urlName.append(":").append(paths[paths.length - 1]));
                            jsonObject.put("tag", EncryptUtil.encrypt(rootPath));
                            jsonArray.add(jsonObject);
                        }
                    }
                }
            }
        }
        return JsonMessage.getString(200, "", jsonArray);
    }
}
